﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using MedLink2011.Core;
using MedLink2011.Views.Patients.ChildWindows;
using MedLink2011.Views.Patients.Reports;
using MedLink2011.Web.Models;
using MedLink2011.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using RelayCommand = MedLink2011.Core.RelayCommand;
using System.Windows.Browser;
using MedLink2011.Controls;

namespace MedLink2011.Views.Patients.ViewModels
{
    public class PrescriptionViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
    {
        public static MedLink2011Context _prescriptionContext;
        private ObservableCollection<Prescription> _prescription;
        private MedLink2011Context _context;
        private EntityQuery<MedLink2011.Web.Models.Diagno> _diagnoQuery;
        private EntityQuery<MedLink2011.Web.Models.Patient> _patientQuery;
        private EntityQuery<MedLink2011.Web.Models.Consultation> _consultationQuery;
        private EntityQuery<MedLink2011.Web.Models.Doctor> _doctorQuery;
        //
       public PrescriptionViewModel()
        {
            if (!IsDesignTime)
            {
                _prescriptionContext = new MedLink2011Context();
                IsBusy = true;
                WireCommands();
                LoadPrescriptionAsync();
                LoadComboBoxData();
            }
        }
        
        #region "Load Current Prescription"
        readonly int loadedPatient_Id = MedLink2011.Views.Patients.ViewModels.PatientViewModel.DashLoad_PK;
        //readonly int loadedPatient_Id = 1;
        private void LoadPrescriptionAsync()
         {
           if (!_prescriptionContext.IsSubmitting)
            {
                if (loadedPatient_Id > 0)
                {
                    PerformAsyncQuery<Prescription>(_prescriptionContext, _prescriptionContext.GetPrescriptionsForPatientsQuery(loadedPatient_Id), PrescriptionLoadedComplete);
                }
                else
                {
                    PerformAsyncQuery<Prescription>(_prescriptionContext, _prescriptionContext.GetPrescriptionsQuery(), PrescriptionLoadedComplete); 
                }
            }
        }

        private EntitySet<Prescription> _prescriptionCollection;
        public EntitySet<Prescription> PrescriptionCollection
        {
            get { return _prescriptionCollection; }
            set
            {
                _prescriptionCollection = value;
                RaisePropertyChanged("PrescriptionCollection");
            }
        }

        private Prescription _currentPrescription;
        public Prescription CurrentPrescription
        {
            get { return _currentPrescription; }
            set
            {
                _currentPrescription = value;
                RaisePropertyChanged("CurrentPrescription");
            }
        }

        #endregion "Load Current Prescription"

        #region Commands

        private void EnableCommands()
        {
            AddNewPrescriptionCommand.IsEnabled = true;
            SavePrescriptionCommand.IsEnabled = true;
            DeletePrescriptionCommand.IsEnabled = true;
            PrintPrescriptionCommand.IsEnabled = true;
            SearchPrescriptionCommand.IsEnabled = true;
            SelectionChangedCommand.IsEnabled = true;
            RowLoadedCommand.IsEnabled = true;
            ShowChartDashboardCommand.IsEnabled = true;
           }

        private void WireCommands()
        {
            AddNewPrescriptionCommand = new RelayCommand(AddPrescription);
            SavePrescriptionCommand = new RelayCommand(SavePrescription);
            DeletePrescriptionCommand = new RelayCommand(DeletePrescription);
            PrintPrescriptionCommand = new RelayCommand(PrintPrescription);
            ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
            SearchPrescriptionCommand = new RelayCommand<string>(SearchInPrescription);
            SelectionChangedCommand = new RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs>(e =>
            {
                var element = e.OriginalSource as UIElement;
                var element2 = e.OriginalSource as Telerik.Windows.Controls.DataControl;

                if ((element2 != null) && (!_toDelete))
                {
                    var _theItem = element2.SelectedItem;
                    CurrentPrescription = (Prescription) _theItem;
            SelectedDiagno =
                DiagnoCollection.Where(c => c.Diagno_Id == CurrentPrescription.Diagno_Id).SingleOrDefault();
            SelectedPatient =
                PatientCollection.Where(c => c.Patient_Id == CurrentPrescription.Patient_Id).SingleOrDefault();
            SelectedConsultation =
                ConsultationCollection.Where(c => c.Consultation_id == CurrentPrescription.Consultation_id).SingleOrDefault();
            SelectedDoctor =
                DoctorCollection.Where(c => c.Doctor_Id == CurrentPrescription.Doctor_Id).SingleOrDefault();
              }
            });
            
            RowLoadedCommand = new RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs>( e =>
                {
                    if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                    {
                        MedLink2011.Web.Models.Prescription model = e.DataElement as MedLink2011.Web.Models.Prescription;
                        var grid = new Grid();
                        var tb = new TextBlock
                               {
                               Text = string.Format(
			"Common Name : {0} \r\n"+
			"Use Generic : {1} \r\n"+
			"Generic Name : {2} \r\n"+
			"Active Ingredient : {3} \r\n"+
			"Dosage : {4} \r\n"+
			"Date Prescribed : {5} \r\n"+
			"Instructions : {6} \r\n"+
			"Side Effects : {7} \r\n"+
			"Status : {8} \r\n"+
			"Pharmacy : {9} \r\n"+
			"Foods To Avoid : {10} \r\n"+
			"Extra Info : {11} \r\n"+
			"Start Treatment : {12} \r\n"+
			"Finish Treatment : {13} \r\n"+
			"Dosage Units : {14} \r\n"+
			"Patient Discontinued Treatment : {15} \r\n"+
			"Reason For Discontinuation : {16} \r\n"+
			"Frequency : {17} \r\n"+
			"Freq Unit : {18} \r\n"+
			"Treatment Duration : {19} \r\n",

			model.Common_Name,
			model.Use_Generic,
			model.Generic_Name,
			model.Active_Ingredient,
			model.Dosage,
			model.Date_Prescribed,
			model.Instructions,
			model.Side_Effects,
			model.Status,
			model.Pharmacy,
			model.Foods_to_avoid,
			model.Extra_Info,
			model.Start_Treatment,
			model.Finish_Treatment,
			model.Dosage_units,
			model.Patient_Discontinued_Treatment,
			model.Reason_for_Discontinuation,
			model.Frequency,
			model.Freq_Unit,
			model.Treatment_Duration
                     ),
                            Margin = new Thickness(3, 3, 3, 3),
                            Opacity = 0.8,
                            MaxWidth = 250,
                            FontSize = 10,
                            TextWrapping = TextWrapping.NoWrap
                                     };
                        grid.Children.Add(tb);
                        ToolTipService.SetToolTip(e.Row, grid);
                    }
                });
                
           }

        public RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs> RowLoadedCommand
        {
            get;
            private set;
        }

        public RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs> SelectionChangedCommand
        {
            get;
            private set;
        }

        public RelayCommand AddNewPrescriptionCommand
        {
            get;
            private set;
        }
        public RelayCommand SavePrescriptionCommand
        {
            get;
            private set;
        }
        public RelayCommand DeletePrescriptionCommand
        {
            get;
            private set;
        }
        public RelayCommand PrintPrescriptionCommand
        {
            get;
            private set;
        }

        public RelayCommand<object> ShowChartDashboardCommand
        {
            get;
            private set;
        }

        public RelayCommand<string>  SearchPrescriptionCommand
        {
            get;
            private set;
        }

        #endregion Commands
        
        private void SearchInPrescription( string searchText)
        {
            MessageBox.Show(searchText);
        }
        
        private void SavePrescription()
        {
            CurrentPrescription.Diagno_Id = SelectedDiagno.Diagno_Id;
            CurrentPrescription.Patient_Id = SelectedPatient.Patient_Id;
            CurrentPrescription.Consultation_id = SelectedConsultation.Consultation_id;
            CurrentPrescription.Doctor_Id = SelectedDoctor.Doctor_Id;
            CurrentPrescription.write_date = CurrentTime;
            CurrentPrescription.write_uid = CurrentUser;
            _prescriptionContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("Prescription se ha actualizado");
                    RaisePropertyChanged("PrescriptionCollection");
                    RaisePropertyChanged("CurrentPrescription");
                }
            }, null);
        }
        #region "Add New"
        //http://forums.silverlight.net/forums/p/193377/449256.aspx
        private void AddPrescription()
        {

            MedLink2011.Web.Models.Prescription prescription = new MedLink2011.Web.Models.Prescription();
            PrescriptionsAddCW addNewWindow = new PrescriptionsAddCW();
            addNewWindow.DataContext = prescription;
            addNewWindow.Closed += (s, ee) =>
            {
                if (addNewWindow.DialogResult == true)
                {
                    prescription.create_date = CurrentTime;
                    prescription.write_date = CurrentTime;
                    prescription.create_uid = CurrentUser;
                    prescription.write_uid = CurrentUser;
                    
                    _prescriptionContext.Prescriptions.Add(prescription);
                    _prescriptionContext.SubmitChanges(p =>
                    {
                        if (p.HasError)
                        {
                            p.MarkErrorAsHandled();
                            ErrorWindow.CreateNew(p.Error);
                        }
                        else
                        {
                            MessageBox.Show("New Prescription has been added");
                        }
                    }, null);
                }
            };
            addNewWindow.Show();
            addNewWindow.Closed += FrmClosedAdd;
        }


        void FrmClosedAdd(object sender, EventArgs e)
        {
            LoadPrescriptionAsync();
        }
        #endregion "Add New"


        private static int _dashload_PK;
        public static int DashLoad_PK
        {
            get { return _dashload_PK; }
            set { _dashload_PK = value ; }
        }


        private void ShowChartDashboard(object selectedItem)
        {
            //
            string a = selectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            DashLoad_PK = dashLoadPk;
            Uri target = new Uri("/Patients/Pages/PatientsTitlePage?Prescription_id=" + DashLoad_PK, UriKind.Relative);

   
            var _theItem = selectedItem;
            CurrentPrescription = (Prescription)_theItem;
            //NavigationService.Navigate(target);
            //var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
            //if (service != null) service.Navigate(target);
        }



        private static int _current_Patient_id;
        public static int Current_Patient_id
        {
            get { return _current_Patient_id; }
            set { _current_Patient_id = value ; }
        }
        
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
        public string CurrentTime
        {
            get
            {
                DateTime time = DateTime.Now;   
                const string format = "MMM ddd d HH:mm yyyy";  
                return (time.ToString(format));
            }
        }

        public string CurrentUser
        {
            get { return WebContext.Current.User.ToString() ; }
        }


        #region "LoadComboBoxData"

            
        public EntitySet<Diagno> DiagnoCollection { get; set; }
        private Diagno _selectedDiagno;
        public  Diagno SelectedDiagno
        {
            get { return _selectedDiagno; }
            set
            {
                _selectedDiagno = value;
                RaisePropertyChanged("SelectedDiagno");
            }
        }
            
        public EntitySet<Patient> PatientCollection { get; set; }
        private Patient _selectedPatient;
        public  Patient SelectedPatient
        {
            get { return _selectedPatient; }
            set
            {
                _selectedPatient = value;
                RaisePropertyChanged("SelectedPatient");
            }
        }
            
        public EntitySet<Consultation> ConsultationCollection { get; set; }
        private Consultation _selectedConsultation;
        public  Consultation SelectedConsultation
        {
            get { return _selectedConsultation; }
            set
            {
                _selectedConsultation = value;
                RaisePropertyChanged("SelectedConsultation");
            }
        }
            
        public EntitySet<Doctor> DoctorCollection { get; set; }
        private Doctor _selectedDoctor;
        public  Doctor SelectedDoctor
        {
            get { return _selectedDoctor; }
            set
            {
                _selectedDoctor = value;
                RaisePropertyChanged("SelectedDoctor");
            }
        }
        private long dtStart = 0;
        private long dtEnd = 0;
        void LoadComboBoxData()
        {
            dtStart = System.DateTime.Now.Ticks;
            
            //Diagno_IdComboBox
            _context = new MedLink2011Context();
            _diagnoQuery = _context.GetDiagnosQuery();
            _diagnoQuery = _diagnoQuery.OrderBy(e => e.Diagno_Id);
            PerformAsyncQuery<Diagno>(_context, _diagnoQuery, Diagno_IdComboBoxLoaded);
            DiagnoCollection = _context.Diagnos;
            
            //Patient_IdComboBox
            _context = new MedLink2011Context();
            _patientQuery = _context.GetPatientsQuery();
            _patientQuery = _patientQuery.OrderBy(e => e.Patient_Id);
            PerformAsyncQuery<Patient>(_context, _patientQuery, Patient_IdComboBoxLoaded);
            PatientCollection = _context.Patients;
            
            //Consultation_idComboBox
            _context = new MedLink2011Context();
            _consultationQuery = _context.GetConsultationsQuery();
            _consultationQuery = _consultationQuery.OrderBy(e => e.Consultation_id);
            PerformAsyncQuery<Consultation>(_context, _consultationQuery, Consultation_idComboBoxLoaded);
            ConsultationCollection = _context.Consultations;
            
            //Doctor_IdComboBox
            _context = new MedLink2011Context();
            _doctorQuery = _context.GetDoctorsQuery();
            _doctorQuery = _doctorQuery.OrderBy(e => e.Doctor_Id);
            PerformAsyncQuery<Doctor>(_context, _doctorQuery, Doctor_IdComboBoxLoaded);
            DoctorCollection = _context.Doctors;
        }
        
        private void Diagno_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Diagno> e)
        {
            if (!e.HasError)
            {
                SelectedDiagno =
                    DiagnoCollection.Where(c => c.Diagno_Id == CurrentPrescription.Diagno_Id).SingleOrDefault();
            }
        }
        private void Patient_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Patient> e)
        {
            if (!e.HasError)
            {
                SelectedPatient =
                    PatientCollection.Where(c => c.Patient_Id == CurrentPrescription.Patient_Id).SingleOrDefault();
            }
        }
        private void Consultation_idComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Consultation> e)
        {
            if (!e.HasError)
            {
                SelectedConsultation =
                    ConsultationCollection.Where(c => c.Consultation_id == CurrentPrescription.Consultation_id).SingleOrDefault();
            }
        }
        private void Doctor_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Doctor> e)
        {
            if (!e.HasError)
            {
                SelectedDoctor =
                    DoctorCollection.Where(c => c.Doctor_Id == CurrentPrescription.Doctor_Id).SingleOrDefault();
            }
        }


        private void PrescriptionLoadedComplete(object sender, MedLink2011.Core.EntityResultsArgs<Prescription> e)
        {
            IsBusy = false;
            if (!e.HasError)
            {
                PrescriptionCollection = _prescriptionContext.Prescriptions;
                CurrentPrescription = PrescriptionCollection.FirstOrDefault();
                EnableCommands();
            SelectedDiagno = DiagnoCollection.Where(c => c.Diagno_Id == CurrentPrescription.Diagno_Id).SingleOrDefault();
            SelectedPatient = PatientCollection.Where(c => c.Patient_Id == CurrentPrescription.Patient_Id).SingleOrDefault();
            SelectedConsultation = ConsultationCollection.Where(c => c.Consultation_id == CurrentPrescription.Consultation_id).SingleOrDefault();
            SelectedDoctor = DoctorCollection.Where(c => c.Doctor_Id == CurrentPrescription.Doctor_Id).SingleOrDefault();

            }
            else
            {
                // notify user if there is any error
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void AddNewForm_Closed(object sender, MedLink2011.Core.EntityResultsArgs<Prescription> e)
        {
            if (!e.HasError)
            {
                
            }
        }


        #endregion "LoadComboBoxData"

        #region "Delete"

        private bool _toDelete=false;

        private void DeletePrescription()
        {
            _toDelete = true;
            var prescriptionToDelete = CurrentPrescription;
           if (prescriptionToDelete != null)
                    {
                     var result = MessageBox.Show("Are you sure you wish to delete the Current Prescription?", "Confirm Delete", MessageBoxButton.OKCancel);
                      if (result.Equals(MessageBoxResult.OK))
                        {
            _prescriptionContext.Prescriptions.Remove(prescriptionToDelete);
            _prescriptionContext.SubmitChanges(o =>
            {
                if (o.HasError)
                {
                    MessageBox.Show("Esta prescription no se puede eliminar ya que existen datos que dependen de esta Prescription.....", "Cancelado", MessageBoxButton.OKCancel);
                    o.MarkErrorAsHandled();
                    _prescriptionContext.RejectChanges();
                }
                else
                {
                    MessageBox.Show("el registro de  prescription ha sido eliminado exitosamente ... ");
                    //LoadPrescriptionAsync();
                    RaisePropertyChanged("PrescriptionCollection");
                    CurrentPrescription = PrescriptionCollection.FirstOrDefault();
                }
            }, null);
            }
       }
            _toDelete = false;
        }
        #endregion "Delete"
        
        #region "Print"
        
        private void PrintPrescription()
        {
            if (CurrentPrescription != null)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
                document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
                string PrintQueue = "Prescriptions_" + CurrentPrescription.ToString(); // to show in the print queue
                document.Print(PrintQueue); //fires when printing has begun
            }
        }
        
        static void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
            }
            else
                MessageBox.Show("Print Complete");
        }
        
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            MedLink2011.Web.Models.Prescription appt = CurrentPrescription as MedLink2011.Web.Models.Prescription;
            if (appt != null)
            {
                //e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
                //if (document.PrintedPageCount > 0)
                //{
                // e.PageVisual = new ChildEntityFReport() { DataContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
                //}
                //else
                e.PageVisual = new PrescriptionsFReport() { DataContext = appt };
            }
        }
       
        #endregion "Print"

    }


}

